//
//  RTJBindPayCardController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/12/5.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJBindPayCardController.h"
#import "RTJUserInfoCommntCell.h"
#import "RTJUserInfoCell.h"
#import "RTJBankTypeListController.h"

@interface RTJBindPayCardController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *idCard;
@property (nonatomic,strong) NSString *bankNum;
@property (nonatomic,strong) NSString *bankID;
@property (nonatomic,strong) NSString *bankName;
@property (nonatomic,strong) NSString *phoneStr;
@property (nonatomic,strong) NSMutableArray *cardArr;
@property (nonatomic,strong) UITextField *textFld;
@property (nonatomic,strong) NSString *codeStr;
@property (nonatomic,strong) NSString *externalRefNumber;
@property (nonatomic,strong) NSString *token;
@property (nonatomic,strong) UIButton *sendSMSBtn;

@property (nonatomic,assign) BOOL isSend;
@property (nonatomic,assign) BOOL isRealNameEditor;
@property (nonatomic,assign) BOOL isIdnoEditor;
@property (nonatomic,assign) BOOL bankType;
@end

@implementation RTJBindPayCardController

-(void)viewWillAppear:(BOOL)animated{
    
    [self.tableView reloadData];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _cardArr  = [NSMutableArray array];
    _bankType = YES;
    self.navigationController.navigationBarHidden = NO;
    self.title = @"绑定银行卡";
    self.tableView.tableFooterView=[UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight=300;
    
    
    UIButton *clear=[UIButton buttonWithType:UIButtonTypeSystem];
    clear.size=CGSizeMake(60, 30);
    [clear setTitle:@"查看限额" forState:UIControlStateNormal];
    [clear setTitleColor:[UIColor colorForHex:@"#666666"] forState:UIControlStateNormal];
    clear.titleLabel.font= [UIFont systemFontOfSize:14];
//    [UIFont fontWithName:@"PingFang-SC-Bold" size:8];
    [clear addTarget:self action:@selector(chakan) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:clear];
    
    _isRealNameEditor = NO;
    _isIdnoEditor = NO;
    //快钱充值支持的银行卡列表
    [self supportBankCardType];
    
}

-(void)chakan{
    
    RTJCommentController *vc = [[RTJCommentController alloc]init];
    vc.title = @"查看限额";
    vc.imgName = @"ckxe";
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)supportBankCardType{
    
    [RTJNetWork asyncRequestWithURL:@"user/get_bank" params:nil method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                NSArray *arr = data[@"data"];
                
                [self.cardArr addObjectsFromArray:arr];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"获取银行卡信息失败:%@",data[@"msg"]]];

            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];

        }       
        
    }];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 7;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"RTJUserInfoCommntCell";
    
    NSInteger idcardpassed = [RTJUserTool getTheUserModel].idcardpassed;//是否实名
    
    NSMutableArray *bankArr = [NSMutableArray array];
    
    [ bankArr addObjectsFromArray:[RTJUserTool getTheUserModel].user_bank ];
    
    RTJUserInfoCommntCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    
        if (indexPath.row == 0) {
    
    if (!cell) {
        
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
        
            }
            
        cell.textFld.tag = 10;
        cell.textFld.delegate = self;
        cell.titleLab.text = @"姓名:";
        cell.textFld.placeholder = @"请输入你的姓名";
//        cell.img.hidden = YES;
        cell.textFld.userInteractionEnabled = idcardpassed == 1 ? NO : YES;
        
        if ([RTJUserTool getTheUserModel].real_name.length !=0&&_isRealNameEditor == NO) {
                
                _name = [RTJUserTool getTheUserModel].real_name;
        }
        cell.textFld.text = idcardpassed == 1 ? [Apputil replaceStringWithAsterisk:[RTJUserTool getTheUserModel].real_name startLocation:1 lenght:[RTJUserTool getTheUserModel].real_name.length -1]:_name;
       
            
    }
    
     else if (indexPath.row == 1){
     
     if (!cell) {
     
         cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
     
     }
         cell.textFld.tag = 20;
         cell.textFld.delegate = self;
//         cell.img.hidden = YES;
         cell.titleLab.text = @"身份证号码:";
         cell.textFld.placeholder = @"请输入身份证号码";
         cell.textFld.userInteractionEnabled = idcardpassed == 1 ? NO : YES;
         
         NSString *idno = [NSString stringWithFormat:@"%ld",[RTJUserTool getTheUserModel].idno];
         
         if (idno.length!=0&&_isIdnoEditor == NO) {
             
             _idCard = idno;
         }
         cell.textFld.text = idcardpassed == 1 ? [NSString stringWithFormat:@"%@",[Apputil replaceStringWithAsterisk:idno startLocation:4 lenght:idno.length -8]]:_idCard;
         
         
     }else if (indexPath.row == 2){
     
     if (!cell) {
     
         cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
     
     }
     cell.titleLab.text = @"银行卡号:";
//     cell.img.hidden = YES;
     cell.textFld.placeholder = @"请输入对应身份证的银行卡号";
     cell.textFld.tag = 30;
     cell.textFld.delegate = self;
     cell.textFld.userInteractionEnabled =  YES;
     cell.textFld.text = _bankNum;
     
     
     }else if (indexPath.row == 3){
     
     if (!cell) {
     
         cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
     
     }
//         cell.img.hidden = YES;
         cell.titleLab.text = @"银行名称:";
         cell.textFld.placeholder = @"请选择银行";
         cell.textFld.text = _bankName;
         cell.textFld.userInteractionEnabled = NO;

     }else if (indexPath.row == 4){
     
     if (!cell) {
     
         cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
     
     }
         cell.textFld.tag = 40;
         cell.textFld.delegate = self;
         cell.titleLab.text = @"手机号码:";
         cell.textFld.placeholder = @"请输入银行卡预留手机号码";
//         cell.img.hidden = YES;
         cell.textFld.text = _phoneStr;

     }else if (indexPath.row ==5){
         
         if (!cell) {
             
             cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][5];
         }
         
         cell.codeTxtFld.delegate = self;
         cell.codeTxtFld.text = _codeStr;
         [cell.sendBtn addTarget:self action:@selector(bindCardForSendCode) forControlEvents:UIControlEventTouchUpInside];
         cell.sendBtn.layer.borderColor = [UIColor colorForHex:@"#e5e5e5"].CGColor;
         cell.sendBtn.layer.borderWidth = 1;
         cell.sendBtn.layer.cornerRadius = 5;
         cell.sendBtn.layer.masksToBounds = YES;
         self.sendSMSBtn = cell.sendBtn;
         
     }else{
     
     if (!cell) {
     
         cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][1];
        }
         
         [cell.bindBtn addTarget:self action:@selector(bindAction:) forControlEvents:UIControlEventTouchUpInside];
        
     }
     
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    _textFld = textField;

}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    NSMutableArray *bankArr = [NSMutableArray array];
    
    [ bankArr addObjectsFromArray:[RTJUserTool getTheUserModel].user_bank ];
    
    _textFld = textField;
    
    if (textField.tag == 10) {
        
        _isRealNameEditor = YES;
        _name = textField.text;
        
    }else if (textField.tag == 20){
        
        _isIdnoEditor = YES;
        _idCard = textField.text;
        
    }else if (textField.tag == 30){
        
        _bankNum = textField.text;

        if (_bankNum.length!=0) {
            
            if (_bankListArr.count!=0) {

                [_bankListArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    if ([obj[@"bankcard"] isEqualToString:self.bankNum]) {

                        *stop = YES;
                        [SVProgressHUD showErrorWithStatus:@"此银行卡已经绑定了哦"];
                        self.bankName = @"";
                        self.bankID = @"";
                        self.bankType = NO;
                        [self.tableView reloadData];
                        

                    }else{

                        *stop = NO;

                    }

                    if (*stop ==YES) {

                        [SVProgressHUD showErrorWithStatus:@"此银行卡已经绑定了哦"];
                       
                    }else{
                        
                        if (*stop == NO&&idx == self.bankListArr.count-1) {
                            
                            //验证银行卡类型
                            [self verifyBankCardType:self.bankNum];
                            
                        }
                    }
                }];

            }else{
                
                //验证银行卡类型
                [self verifyBankCardType:_bankNum];
            }

        }
        
    }else if (textField.tag == 500){
        
        _codeStr = textField.text;
        
    }else{
        
        _phoneStr = textField.text;

        }
    
}

 //验证银行卡类型
-(void)verifyBankCardType:(NSString *)bankNum{
    
    [RTJNetWork asyncRequestWithURL:@"query/get_bank_info" params:@{@"bankcard":bankNum} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {

                self.bankName = [NSString stringWithFormat:@"%@",data[@"data"][@"bank_name"]];
                self.bankID = [NSString stringWithFormat:@"%@",data[@"data"][@"bank_id"]];
                self.bankType = YES;
                [self.tableView reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"验正银行卡类型失败:%@",data[@"msg"]]];
                
                self.bankName = @"";
                self.bankID = @"";
                self.bankType = NO;
                [self.tableView reloadData];

            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            self.bankName = @"";
            self.bankID = @"";
            self.bankType = NO;
            [self.tableView reloadData];
        }
 
    }];
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_textFld resignFirstResponder];

}

//绑定银行卡快钱发送验证码
-(void)bindCardForSendCode{
    
    NSInteger idcardpassed = [RTJUserTool getTheUserModel].idcardpassed;
    
    NSDictionary *dic = nil;
    
     if (idcardpassed == 1){//已实名
             
             if (_bankNum.length == 0 ) {

                 [SVProgressHUD showErrorWithStatus:@"请填写银行卡卡号"];
                 return;
             }

             if (_phoneStr.length == 0) {

                 [SVProgressHUD showErrorWithStatus:@"请正确填写银行预留手机号"];
                 return;
             }
         
                 //这种情况是从没有绑定过银行卡

                 dic = @{
                         @"bankcard":_bankNum,
                         @"real_name":[RTJUserTool getTheUserModel].real_name,
                         @"idno":[NSString stringWithFormat:@"%ld",(long)[RTJUserTool getTheUserModel].idno],
                         @"reserve_mobile":_phoneStr
                         };
             
 
     }else{
         
         if (_name.length == 0 ) {
             
             [SVProgressHUD showErrorWithStatus:@"请填写姓名"];
             return;
         }
         
         if (_idCard.length == 0 ) {
             
             [SVProgressHUD showErrorWithStatus:@"请填写身份证号"];
             return;
         }
         
         if (_idCard.length != 18 ) {
             
             [SVProgressHUD showErrorWithStatus:@"请正确填写身份证号"];
             return;
         }
         
         if (_bankNum.length == 0 ) {
             
             [SVProgressHUD showErrorWithStatus:@"请填写银行卡卡号"];
             return;
         }
         
         if (_phoneStr.length == 0) {
             
             [SVProgressHUD showErrorWithStatus:@"请正确填写银行预留手机号"];
             return;
         }
         
         dic = @{
                 @"bankcard":_bankNum,
                 @"real_name":_name,
                 @"idno":_idCard,
                 @"reserve_mobile":_phoneStr
                 };
     }
    
    [SVProgressHUD showWithStatus:nil];

    [RTJNetWork asyncRequestWithURL:@"user/kq_bank_send_code" params:dic method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                if ([data[@"data"][@"status"]integerValue] == 1) {
                    
                    [self.sendSMSBtn startWithTime: 60 title:@"重新获取验证码" countDownTitle:@"s" mainColor:[UIColor whiteColor] countColor:[UIColor whiteColor]];
                    self.externalRefNumber = [NSString stringWithFormat:@"%@",data[@"data"][@"data"][@"externalRefNumber"]];
                    self.token = [NSString stringWithFormat:@"%@",data[@"data"][@"data"][@"token"]];
                    
                    [SVProgressHUD showSuccessWithStatus:@"验证码已发送，请注意查收"];
                    self.isSend = YES;
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"验证码发送失败:%@",data[@"data"][@"msg"]]];
                    
                }
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"验证码发送失败:%@",data[@"msg"]]];
                
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
        }
    }];
}


-(void)bindAction:(UIButton *)btn{
    
    [_textFld resignFirstResponder];

    if (self.isSend == NO) {
        
        [SVProgressHUD showErrorWithStatus:@"请先获取验证码进行绑定银行卡"];
        return;
    }
    
    [SVProgressHUD showWithStatus:nil];
    NSDictionary *dic = nil;
    
    NSInteger idcardpassed = [RTJUserTool getTheUserModel].idcardpassed;
    
    if (_bankNum.length == 0 ) {
        
        [SVProgressHUD showErrorWithStatus:@"请填写银行卡卡号"];
        return;
    }
    
    if (_bankNum.length >19) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确填写银行卡卡号"];
        return;
    }
    
    if (15>_bankNum.length) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确填写银行卡卡号"];
        return;
    }
    
    
    if (_bankID.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确选择银行类型"];
        return;
    }

    if (_phoneStr.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确填写银行预留手机号"];
        return;
    }
    
    if (idcardpassed == 1) {//已实名
        
        dic = @{
                @"bankcard":_bankNum,
                @"bank_id":_bankID,
                @"reserve_mobile":_phoneStr,
                @"validCode":_codeStr,
                @"externalRefNumber":_externalRefNumber,
                @"token":_token
                };
        
    }else{
        //未实名
        
        if (_name.length == 0 ) {
            
            [SVProgressHUD showErrorWithStatus:@"请填写姓名"];
            return;
        }
        
        if (_idCard.length == 0 ) {
            
            [SVProgressHUD showErrorWithStatus:@"请填写身份证号"];
            return;
        }
        
        if (_idCard.length != 18 ) {
            
            [SVProgressHUD showErrorWithStatus:@"请正确填写身份证号"];
            return;
        }
        
        dic = @{
                @"bankcard":_bankNum,
                @"bank_id":_bankID,
                @"real_name":_name,
                @"idno":_idCard,
                @"reserve_mobile":_phoneStr,
                @"validCode":_codeStr,
                @"externalRefNumber":_externalRefNumber,
                @"token":_token
                };
    }
    
    [RTJNetWork asyncRequestWithURL:@"user/add_bank" params:dic method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                [SVProgressHUD showSuccessWithStatus:@"绑定银行卡成功"];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"绑定银行卡失败:%@",data[@"msg"]]];
                
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];

        }
    }];
    
}

@end
